<template>
  <a-modal
    :visible="visible"
    @cancel="()=>{visible=false}"
    @ok="submit"
    title="升级策略选择"
    width="1000px"
    dialogClass="strategy-selector"
    :bodyStyle="{ height: '500px', overflowY: 'auto' }"
  >
    <a-form ref="strategySeletorForm" class="listSearchWrap table-page-search-wrapper">
      <a-row :gutter="[16,0]">
<!--        <a-col :span="4" :xs="24" :md="12" :lg="6">-->
<!--          <UpgradeTriggerTypeSelect v-model="queryParams.upgradeTriggerType" :disabled="!!upgradeTriggerType" class="version-type-select" style="width: 100%;"/>-->
<!--        </a-col>-->
        <a-col
          :xs="24"
          :sm="12"
          :md="8"
          :lg="6">
          <a-form-item :colon="false">
            <a-input v-model.trim="queryParams.name" :placeholder="$t('pleaseInput') + $t('policyName')" allowClear />
          </a-form-item>
        </a-col>
        <a-col :span="4" :xs="24" :md="12" :lg="6">
          <!--: 数据量过大，过滤改为后端实现 filter-option="filterOption"  option-filter-prop="children"-->
          <a-select
            v-model="queryParams.modelId"
            :allow-clear="true"
            :show-search="true"
            :filterOption="false"
            @search="getModelData"
            @blur="getModelData('')"
            :disabled="false"
            :placeholder="$t('pleaseSelect') + $t('vehicleModel')"
            :maxTagCount="10"
          >
            <a-select-option v-for="item in modelOptions" :title="item.name" :key="item.id" :value="item.id">
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-col>
        <a-col
          :xs="24"
          :sm="12"
          :md="8"
          :lg="6">
          <a-form-item :colon="false">
            <vehicle-version-select
              mode="multiple"
              :only-version-type="versionType"
              v-model="queryParams.vehicleVersionId"
              @changeoption="(val) => {queryParams.vehicleVersionId = val}"
            ></vehicle-version-select>
          </a-form-item>
        </a-col>

        <a-col
          :xs="24"
          :sm="24"
          :md="24"
          :lg="4"
          class="btnWarp">
          <a-form-item class="searchBtns">
            <auth-button type="info" :auth="strategyPerms[testType].USER.fotaSjcl.view" @click="$refs.table.refresh(true)">
              <i class="iconfont icon-chazhao"></i>
              {{ $t('inquiry') }}
            </auth-button>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <s-table
      :columns="commonColumns"
      :data="load"
      :scrollX="900"
      row-key="id"
      style="height:calc(100% - 100px);"
      ref="table"
      :customRow="customRow"
      :row-selection="{ type:'radio',selectedRowKeys: selectedRowKeys, onChange: onSelectChange,getCheckboxProps:onGetCheckboxProps }"
    >
      <template slot-scope="text" v-for="column in commonColumns" :slot="column.scopedSlots.customRender">
        {{text}}
      </template>
      <template slot="name" slot-scope="text,record">
        <a-button type="link"
          @click="() => {currentId=record.id;$refs.showStrategy.visible=true}"
        >
          <table-ellipsis :text="text"></table-ellipsis>
        </a-button>
      </template>
      <template slot="status" slot-scope="text,record">
        <table-ellipsis :text="record.enabled === false ? $t('stoped') : (strategyStatusObj[text] || '-')">
        </table-ellipsis>
      </template>
      <template slot="action" slot-scope="text,record">
        <a-button type="link"
          @click="() => {currentId=record.id;$refs.showStrategy.visible=true}"
        >
          详情
        </a-button>
      </template>
    </s-table>
    <!-- 查看策略 -->
    <show-condition-update-strategy
      ref="showStrategy"
      :updataStrategyId="currentId"
    ></show-condition-update-strategy>
  </a-modal>

</template>
<script>
  import UpgradeTriggerTypeSelect from '@/views/components/UpgradeTriggerTypeSelect'
  import VehicleVersionSelect from '@/views/components/VehicleVersionSelect'
  import { strategyPerms } from '@/config/permission/index'
  import AuthButton from '@/components/AuthButton'
  import { STable } from '@/components'
  import ShowConditionUpdateStrategy from '@/views/components/ShowConditionUpdateStrategy'
  import tableEllipsis from '@/components/Ellipsis/TableEllipsis'
  import i18n from "../../../lang";
  import strategyApi from '@/api/modules/strategy'
  import modelApi from '@/api/modules/system/modelMana'
  import lodash from 'lodash'

  export default {
    components: {
      tableEllipsis,
      ShowConditionUpdateStrategy,
      UpgradeTriggerTypeSelect,
      VehicleVersionSelect,
      AuthButton,
      STable,
    },
    computed:{
      strategyStatusObj () {
      return this.$store.getters.getDictCodeObj('strategyStatusDictCode')
    }
    },
    props: {
      versionType: {
        type: String,
        default: ''
      },
      testType: {
        type: String,
        default: ''
      },
      upgradeTriggerType: {
        type: String,
        default: ''
      },
    },
    data (){
      return {
        visible: false,
        strategyPerms,
        currentId: null,
        queryParams: {
          upgradeTriggerType: this.upgradeTriggerType || 'USER',
          modelId:undefined,
          vehicleVersionId:undefined
        },
        modelOptions: [],
        selectedRowKeys:[],
        commonColumns : [
          {
            title: i18n.t('policyName'),
            dataIndex: 'name',
            scopedSlots: { customRender: 'name' },
            special: true,
            width: 300
          }, {
            title: i18n.t('modelName'),
            dataIndex: 'modelName',
            scopedSlots: { customRender: 'modelName' },
            // width: '170px'
          }, 
          // {
          //   title: i18n.t('trimLevel'),
          //   dataIndex: 'trimLevel',
          //   scopedSlots: { customRender: 'trimLevel' },
          //   // width: '170px'
          // },
          {
            title: i18n.t('vehicleVersion'),
            dataIndex: 'vehicleVersionName',
            scopedSlots: { customRender: 'vehicleVersion' },
            special: true,
            // width: '130px'
          },
          {
            title: i18n.t('policyStatus'),
            dataIndex: 'status',
            scopedSlots: { customRender: 'status' },
            special: true,
            // width: 100
          },
          {
            title: i18n.t('operation'),
            dataIndex: 'action',
            scopedSlots: { customRender: 'action' },
            special: true,
            width: 80
          },
        ],
      }
    },
    mounted() {
      this.$store.dispatch('getStrategyStatusDictCodeData')
    },
    watch:{
      visible(val) {
        if (val) {
          this.queryParams.name=undefined
          this.queryParams.modelId=undefined
          this.queryParams.vehicleVersionId=undefined
          this.getModelData();
          // this.selectedRowKeys = [];
          this.$refs.table && this.$refs.table.loadData()
        }
      },
      upgradeTriggerType(val) {
        this.queryParams.upgradeTriggerType = val
      }
    },
    methods :{
      onGetCheckboxProps: (record) => ({
      // 策略停用不能被选择
      props: {
        //研发、通道测试不能选已发布
        disabled: record.enabled === false /*|| (record.testType !== 'UAT' && record.status === 9)*/
      }
    }),
      setSelectedRowKey(id) {
        this.selectedRowKeys = [];
        if (id) {
          this.selectedRowKeys.push(id);
        }
      },
      customRow(record, index) {
        return {
          on: {
            click: () => {
                if (record.enabled) {
                    this.selectedRowKeys = [record.id];
                }
            },
          },
        };
      },
      submit() {
        if (this.selectedRowKeys.length === 0) {
          this.$message.error("请选择升级策略");
          // this.$error({content:"请选择升级策略", maskClosable: true});
          return;
        }
        this.visible=false;
        this.$emit('ok', this.selectedRowKeys[0]);
      },
      load(parameter) {
        return strategyApi.getStrategyPageData({ ...this.queryParams, type: 1, ...parameter, status: this.versionType === 'PROD' ? 'PUBLISHED' : null}, this.testType, this.queryParams.upgradeTriggerType)
      },
      onSelectChange(selectedRowKeys) {
        this.selectedRowKeys = selectedRowKeys;
      },
      getModelData:lodash.debounce(function(value = '') {
        value = Array.isArray(value) ? '': value
        modelApi.getMyAllModelCode({...this.query,searchWord: value}).then((res) => {
          let data = res.data
          if (!data) {
            return
          }
          data = data.map(item => {
            let showName = item.code
            showName += (item.name ? '[' + item.name + ']' : '')
            // 加code与trimLevel是为了有些地方选择的时候需要这两个参数
            return {
              id: item.code,
              ...item,
              showName,
              code: item.code,
              title: item.name
            }
          })
          this.modelOptions = this.hasAll ? [
            {
              id: '',
              name: this.$t('all')
            }
          ].concat(data) : data
        })
      },500),
    }
  }
</script>
<style lang="less" scoped>
  .ant-btn-link{
    padding: 0;
  }
</style>